package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import io.renren.common.exception.RRException;
import io.renren.common.key.keyConfig;
import io.renren.common.utils.*;
import io.renren.config.ConfigBeanValue;
//import io.renren.modules.app.client.FileClient;
import io.renren.modules.app.dao.PayInfoDao;
import io.renren.modules.app.entity.PayInfoEntity;
import io.renren.modules.app.request.BdcJfQueryRequest;
import io.renren.modules.app.request.JhdzQueryRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.jdom.JDOMException;
import org.jpos.iso.ISOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.renren.modules.app.service.H5payService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Service("h5payService")
public class H5payServiceImpl extends ServiceImpl<PayInfoDao, PayInfoEntity> implements H5payService {

    @Autowired
    private ConfigBeanValue configBeanValue;


    /***
     * 1.1银行缴费查询接口
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RRException.class})
    public Map bdcJfQuery(BdcJfQueryRequest request) throws RRException {
        String bankURL = configBeanValue.outConnClientCcbMainUrl;
        String url = configBeanValue.outConnClientBdcJfQuery;
        try {

            String transactionKey = keyConfig.getInstance().getTransactionKey();
            String mackey = keyConfig.getInstance().getMacKey();
            Gson gson = new Gson();
            Map params = new HashMap();
            log.debug("第一步：查询分行账单信息");
            log.debug("业务号：" + request.getYwh());
            String value = "&ywh=" + URLEncoder.encode(AESUtil.Encrypt(request.getYwh(), transactionKey), "UTF-8");
            log.debug("查询参数：" + value);
            log.debug("查询路径：" + url);
            String retStr = HttpClientUtils.sendPost(url, value);
            log.debug("查询返回结果集(密文)：" + retStr);
            if (!StringUtil.isEmpty(retStr)) {
                String retStr1 = URLDecoder.decode(retStr, "UTF-8");
                log.debug("查询返回结果集(编码)：" + retStr1);
                String retStr2 = AESUtil.Decrypt(retStr1, transactionKey);
//                log.debug("查询返回结果集(解密)：" + retStr2);

                Map retMap = gson.fromJson(retStr2, Map.class);
                if (retMap != null && "200".equals(retMap.get("rspcode"))) {
                    LinkedTreeMap msgMap = (LinkedTreeMap) retMap.get("rspmsg");
                    String orderid = retMap.get("order_id") + "";//PayUtil.getTradeNo();

                    log.debug("MAC:校验");
                    String MAC = retMap.get("mac") + "";
                    String macnew = ISOUtil.dumpString(MacUtils.makeMAC(mackey.getBytes(), (request.getYwh() + orderid).getBytes()));

                    if (!MAC.equals(macnew)) {
                        keyConfig.getInstance().initMacKey();
                        throw new RRException("MAC异常");
                    }
                    log.debug("是否缴费:" + msgMap.get("是否缴费") + "");
                    if ("Y".equals(msgMap.get("是否缴费"))) {
                        throw new RRException("您已支付成功");
                    }


                    log.debug("第二步：保存查询分行数据信息");
                    QueryWrapper<PayInfoEntity> qw = new QueryWrapper<>();
                    qw.eq("BUSI_NO", request.getYwh());
                    qw.eq("TYPE", "Y");
                    int count = baseMapper.selectCount(qw);
                    if (count == 0) {

                        PayInfoEntity entity = new PayInfoEntity();
                        if (msgMap.get("PID") != null) {
                            entity.setPid(new Double(msgMap.get("PID") + "").intValue() + "");
                        } else {
                            entity.setPid("");
                        }

                        entity.setArea(msgMap.get("区属") + "");
                        entity.setOrderId(orderid);
                        entity.setMoney(new BigDecimal(msgMap.get("应缴金额") + ""));

                        entity.setBusiNo(msgMap.get("业务号") + "");

                        entity.setCertNo(msgMap.get("权利人证件号") + "");

                        entity.setType("N");
                        entity.setCompare("N");
                        entity.setBusType(request.getType());
                        baseMapper.insert(entity);

                        log.debug("第二步：封装调用聚合支付URL参数");
                        StringBuffer sb = new StringBuffer();
                        sb.append("MERCHANTID=" + configBeanValue.outConnClientMerchantId);//商户代码
                        sb.append("&POSID=" + configBeanValue.outConnClientCounterId);//商户柜台代码
                        sb.append("&BRANCHID=" + "420000000");//分行代码
                        sb.append("&ORDERID=" + orderid);//定单号
//                        sb.append("&PAYMENT=" + "0.01");//付款金额
                        sb.append("&PAYMENT=" + msgMap.get("应缴金额"));//付款金额
                        sb.append("&CURCODE=" + "01");//币种
                        sb.append("&TXCODE=" + "520100");//交易码
                        sb.append("&REMARK1=" + "");
                        sb.append("&REMARK2=" + "");
                        sb.append("&TYPE=" + "1");
                        sb.append("&PUB=" + configBeanValue.publickeysub30);//公钥后30位 publickeysub30
                        sb.append("&GATEWAY=" + "");
                        sb.append("&CLIENTIP=" + "");
                        sb.append("&REGINFO=" + "");
                        sb.append("&PROINFO=" + "");
                        sb.append("&REFERER=" + "");
                        log.debug("params:" + sb);
                        String mac = MD5Utils.getMD5(sb.toString());
                        log.debug("MAC:" + mac);
                        String URL3 = bankURL + "?" + sb + "&MAC=" + mac + "&PAYMAP=1100000000";
                        log.debug("URL3:" + URL3);
                        params.put("quite", msgMap.get("区属"));
//                        params.put("money", "0.01");
                        params.put("money", msgMap.get("应缴金额"));
                        params.put("name", msgMap.get("权利人名称"));
                        params.put("busiNo", msgMap.get("业务号"));
                        params.put("url", URL3);
                        return params;
                    } else {
                        throw new RRException("您已支付成功");
                    }
                } else if (retMap != null && "498".equals(retMap.get("rspcode"))) {
                    keyConfig.getInstance().initMacKey();
                    throw new RRException(retMap.get("rspmsg") + "");
                } else if (retMap != null && "499".equals(retMap.get("rspcode"))) {
                    keyConfig.getInstance().initTransKey();
                    throw new RRException(retMap.get("rspmsg") + "");
                } else {
                    if (retMap == null) {
                        keyConfig.getInstance().initTransKey();
                        throw new RRException("" + retStr2);
                    } else {
                        throw new RRException(retMap.get("rspmsg") + "");
                    }
                }
            } else {
                throw new RRException("接口调用错误");
            }
        } catch (Exception e) {
            log.error("bdcJfQuery异常", e);
            throw new RRException(e.getMessage());
        }
    }

    /***
     *1.2银行缴费回调接口
     * @param request
     * @param response
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RRException.class})
    public String notify(HttpServletRequest request, HttpServletResponse response) throws RRException {

        String url = configBeanValue.outConnClientInsertTysJsxx;

        //交易密钥
        String transactionKey = keyConfig.getInstance().getTransactionKey();
        String mackey = keyConfig.getInstance().getMacKey();
        log.info("url：" + url);
        PrintWriter out = null;
        log.info("第一步");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        try {
            log.info("第二步");
            log.info("支付回调已进入");

            String POSID = request.getParameter("POSID");
            String BRANCHID = request.getParameter("BRANCHID");
            String ORDERID = request.getParameter("ORDERID");
            String PAYMENT = request.getParameter("PAYMENT");
            String CURCODE = request.getParameter("CURCODE");
            String REMARK1 = request.getParameter("REMARK1");
            String REMARK2 = request.getParameter("REMARK2");
            String ACC_TYPE = request.getParameter("ACC_TYPE");
            String SUCCESS = request.getParameter("SUCCESS");
            String TYPE = request.getParameter("TYPE");
            String REFERER = request.getParameter("REFERER");
            String CLIENTIP = request.getParameter("CLIENTIP");
            String ACCDATE = request.getParameter("ACCDATE");
            String USRMSG = request.getParameter("USRMSG");
            String USRINFO = request.getParameter("USRINFO");
            String PAYTYPE = request.getParameter("PAYTYPE");
            String SIGN = request.getParameter("SIGN");
            String PAYMENT_DETAILS = request.getParameter("PAYMENT_DETAILS");
            log.info("支付返回结果：" + ORDERID);
            log.info("[POSID:" + POSID + "]");
            log.info("[BRANCHID:" + BRANCHID + "]");
            log.info("[ORDERID:" + ORDERID + "]");
            log.info("[PAYMENT:" + PAYMENT + "]");
            log.info("[CURCODE:" + CURCODE + "]");
            log.info("[REMARK1:" + REMARK1 + "]");
            log.info("[REMARK2:" + REMARK2 + "]");
            log.info("[ACC_TYPE:" + ACC_TYPE + "]");
            log.info("[SUCCESS:" + SUCCESS + "]");
            log.info("[TYPE:" + TYPE + "]");
            log.info("[REFERER:" + REFERER + "]");
            log.info("[CLIENTIP:" + CLIENTIP + "]");
            log.info("[ACCDATE:" + ACCDATE + "]");
            log.info("[USRMSG:" + USRMSG + "]");
            log.info("[USRINFO:" + USRINFO + "]");
            log.info("[PAYTYPE:" + PAYTYPE + "]");
            log.info("[SIGN:" + SIGN + "]");
            log.info("[PAYMENT_DETAILS:" + PAYMENT_DETAILS + "]");

            QueryWrapper<PayInfoEntity> qw = new QueryWrapper<>();
            qw.eq("ORDER_ID", ORDERID);
            PayInfoEntity entity = baseMapper.selectOne(qw);
            //商户客户端数据查询交易是否成功
            if (!sendSocketRequest(ORDERID, entity)) {
                Map returnMap = new HashMap();
                returnMap.put("ERRMSG", "商户客户端查询失败(notify)");
                returnMap.put("RESULT", "N");

                entity.setBusStatus("2");
                entity.setRemarks("商户客户端查询失败");
                baseMapper.updateById(entity);

                return new Gson().toJson(returnMap);
            } else {
                entity.setBusStatus("1");
                baseMapper.updateById(entity);
            }


            log.info("第三步:通知分行支付成功");
            StringBuffer value = new StringBuffer();
            value.append("&ywh=" + URLEncoder.encode(AESUtil.Encrypt(entity.getBusiNo(), transactionKey), "UTF-8"));//业务号
            value.append("&pid=" + URLEncoder.encode(AESUtil.Encrypt(entity.getPid(), transactionKey), "UTF-8"));//pid
            value.append("&qs=" + URLEncoder.encode(AESUtil.Encrypt(entity.getArea(), transactionKey), "UTF-8"));//区属
            value.append("&skyh=" + URLEncoder.encode(AESUtil.Encrypt("4", transactionKey), "UTF-8"));//收款银行
            if ("WX".equals(ACC_TYPE)) {
                value.append("&jffs=" + URLEncoder.encode(AESUtil.Encrypt("1", transactionKey), "UTF-8"));//缴费方式
            }
            if ("AL".equals(ACC_TYPE)) {
                value.append("&jffs=" + URLEncoder.encode(AESUtil.Encrypt("2", transactionKey), "UTF-8"));//缴费方式
            }
            value.append("&jfje=" + URLEncoder.encode(AESUtil.Encrypt(entity.getMoney().toString(), transactionKey), "UTF-8"));//缴费金额
            value.append("&jfsj=" + URLEncoder.encode(AESUtil.Encrypt(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN), transactionKey), "UTF-8"));//缴费时间
            value.append("&order_id=" + URLEncoder.encode(AESUtil.Encrypt(entity.getOrderId(), transactionKey), "UTF-8"));//订单号
            String macKey = ISOUtil.dumpString(MacUtils.makeMAC(mackey.getBytes(), (entity.getBusiNo() + entity.getOrderId()).getBytes()));
//            String macKey = AESUtil.Encrypt(entity.getBusiNo() + entity.getOrderId(), mackey);
            value.append("&MAC=" + macKey);//MAC
            log.debug("传参：" + value.toString());
            log.debug("路径：" + url);
            String retStr = HttpClientUtils.sendPost(url, value.toString());
            log.info("支付结果通知：" + retStr);
            retStr = AESUtil.Decrypt(URLDecoder.decode(retStr, "UTF-8"), transactionKey);
//            log.debug("查询返回结果集(解密)：" + retStr);
            Map retMap = new Gson().fromJson(retStr, Map.class);
            Map returnMap = new HashMap();
            if (retMap != null && "200".equals(retMap.get("rspcode"))) {
                log.info("第四步:更新订单流水状态(支付成功)");
                entity.setType("Y");
                entity.setAccType(ACC_TYPE);
                baseMapper.updateById(entity);
                returnMap.put("ERRMSG", "成功");
                returnMap.put("RESULT", "Y");
            } else if (retMap != null && "498".equals(retMap.get("rspcode"))) {
                keyConfig.getInstance().initMacKey();
                returnMap.put("ERRMSG", "失败");
                returnMap.put("RESULT", "N");
            } else if (retMap != null && "499".equals(retMap.get("rspcode"))) {
                keyConfig.getInstance().initTransKey();
                returnMap.put("ERRMSG", "失败");
                returnMap.put("RESULT", "N");
            } else {
                returnMap.put("ERRMSG", "失败");
                returnMap.put("RESULT", "N");
            }


            return new Gson().toJson(returnMap);
        } catch (Exception e) {
            log.error("notify异常", e);
            Map returnMap = new HashMap();
            returnMap.put("ERRMSG", "失败");
            returnMap.put("RESULT", "N");
            return new Gson().toJson(returnMap);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private boolean sendSocketRequest(String orderid, PayInfoEntity entity) {
        try {
            String sRequest = "<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?>  \n" +
                    "<TX>  \n" +
                    "  <REQUEST_SN>01</REQUEST_SN>  \n" +
                    "  <CUST_ID>" + configBeanValue.outConnClientMerchantId + "</CUST_ID>  \n" +
                    "  <USER_ID>" + configBeanValue.outConnClientOperator + "</USER_ID>  \n" +
                    "  <PASSWORD>" + configBeanValue.paypassword + "</PASSWORD>  \n" +
                    "  <TX_CODE>5W1002</TX_CODE>  \n" +
                    "  <LANGUAGE>CN</LANGUAGE>  \n" +
                    "  <TX_INFO>  \n" +
                    "    <START>20190101</START>  \n" +
                    "    <STARTHOUR>00</STARTHOUR>  \n" +
                    "    <STARTMIN>00</STARTMIN>  \n" +
                    "    <END>20190101</END>  \n" +
                    "    <ENDHOUR>00</ENDHOUR>  \n" +
                    "    <ENDMIN>00</ENDMIN>  \n" +
                    "    <KIND>1</KIND>  \n" +
                    "    <ORDER>" + orderid + "</ORDER>  \n" +
                    "    <ACCOUNT></ACCOUNT>  \n" +
                    "    <DEXCEL></DEXCEL>  \n" +
                    "    <MONEY></MONEY>  \n" +
                    "    <NORDERBY>2</NORDERBY>  \n" +
                    "    <PAGE></PAGE>  \n" +
                    "    <POS_CODE></POS_CODE>  \n" +
                    "    <STATUS>3</STATUS>  \n" +
                    "  </TX_INFO>  \n" +
                    "</TX>";

            String resxml = SocketUtils.sendSocketRequest(configBeanValue.outConnClientIp, new Integer(configBeanValue.outConnClientPort), sRequest);
            log.debug("返回结果集：" + resxml);
            Map<String, String> restmap = XmlUtil.doXMLParse(resxml);
            Map<String, String> txInfo = XmlUtil.doXMLParse("<?xml version=\"1.0\" encoding=\"GB18030\"?><TX_INFO>" + restmap.get("TX_INFO") + "</TX_INFO>");
            Map<String, String> list = XmlUtil.doXMLParse("<?xml version=\"1.0\" encoding=\"GB18030\"?><LIST>" + txInfo.get("LIST") + "</LIST>");
            if ("1".equals(list.get("ORDER_STATUS"))) {
                if (entity.getMoney().compareTo(new BigDecimal(list.get("PAYMENT_MONEY") + "")) == 0) {
                    return true;
                } else {
                    entity.setBusStatus("3");
                    entity.setAtMoney(new BigDecimal(list.get("PAYMENT_MONEY") + ""));
                    entity.setRemarks("实缴金额和应缴金额不符");
                    baseMapper.updateById(entity);
                    return false;
                }
            }

            entity.setBusStatus("2");
            entity.setRemarks("商户客户端查询失败");
            baseMapper.updateById(entity);
            return false;

        } catch (JDOMException e) {
            log.error("sendSocketRequest异常", e);
            return false;
        } catch (IOException e) {
            log.error("sendSocketRequest异常", e);
            return false;
        }

    }

    /***
     * 1.3查询聚合支付对账数据
     * @param date
     * @return
     */

    @Override
    @Transactional(rollbackFor = {RRException.class})
    public boolean jhdzQuery(String date) throws RRException {
        Map map = new HashMap();
        String url = configBeanValue.outConnClientUpLoadBillFile;
        File newfile = null;
        String dir = "";
        log.debug("第一步：查询对账文件名" + date);
        OutputStream fw = null;
        try {
            String transactionKey = keyConfig.getInstance().getTransactionKey();
            String sRequest = "<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?>  \n" +
                    "<TX>  \n" +
                    "  <REQUEST_SN>01</REQUEST_SN>  \n" +
                    "  <CUST_ID>" + configBeanValue.outConnClientMerchantId + "</CUST_ID>  \n" +
                    "  <USER_ID>" + configBeanValue.outConnClientOperator + "</USER_ID>  \n" +
                    "  <PASSWORD>" + configBeanValue.paypassword + "</PASSWORD>  \n" +
                    "  <TX_CODE>5W1005</TX_CODE>  \n" +
                    "  <LANGUAGE>CN</LANGUAGE>  \n" +
                    "  <TX_INFO>  \n" +
                    "    <DATE>" + date + "</DATE>  \n" +
                    "    <KIND>1</KIND>  \n" +
                    "    <FILETYPE>1</FILETYPE>  \n" +
                    "    <TYPE>0</TYPE>  \n" +
                    "    <NORDERBY>1</NORDERBY>  \n" +
                    "    <POS_CODE></POS_CODE>  \n" +
                    "    <ORDER></ORDER>  \n" +
                    "    <STATUS>1</STATUS>  \n" +
                    "  </TX_INFO>  \n" +
                    "</TX>";
            String resxml = SocketUtils.sendSocketRequest(configBeanValue.outConnClientIp, new Integer(configBeanValue.outConnClientPort), sRequest);
            log.debug("返回结果集：" + resxml);
            Map<String, String> restmap = XmlUtil.doXMLParse(resxml);
            Map<String, String> txInfo = XmlUtil.doXMLParse("<?xml version=\"1.0\" encoding=\"GB18030\"?><TX_INFO>" + restmap.get("TX_INFO") + "</TX_INFO>");
            String fileName = txInfo.get("FILE_NAME");
            log.debug(date + "对账文件名：" + fileName);
            if (fileName != null) {
                log.debug(date + "第二步：获取对账文件");
                String sRequest1 = "<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\" ?>  \n" +
                        "<TX>  \n" +
                        "  <REQUEST_SN>2007626104811</REQUEST_SN>  \n" +
                        "  <CUST_ID>" + configBeanValue.outConnClientMerchantId + "</CUST_ID>  \n" + //outConnClientMerchantId
                        "  <USER_ID>" + configBeanValue.outConnClientOperator + "</USER_ID>  \n" +
                        "  <PASSWORD>" + configBeanValue.paypassword + "</PASSWORD>  \n" +
                        "  <TX_CODE>6W0111</TX_CODE>  \n" +
                        "  <LANGUAGE>CN</LANGUAGE>  \n" +
                        "  <TX_INFO>  \n" +
                        "    <SOURCE>" + fileName + "</SOURCE>  \n" +
                        "    <FILEPATH>merchant/shls</FILEPATH>  \n" +
                        "    <LOCAL_REMOTE>0</LOCAL_REMOTE>  \n" +
                        "  </TX_INFO>  \n" +
                        "</TX>";
                String resxml1 = SocketUtils.sendSocketRequest(configBeanValue.outConnClientIp, new Integer(configBeanValue.outConnClientPort), sRequest1);
                log.debug("返回结果集：" + resxml1);
                Map<String, String> restmap1 = XmlUtil.doXMLParse(resxml1);
                String returnCode = restmap1.get("RETURN_CODE");
                if ("000000".equals(returnCode)) {
                    log.debug(date + "对账文件名：" + fileName + "获取文件成功");
                    String dirs = configBeanValue.outConnClientDownload;
                    //创建需要发送的文件备用
                    File newDir = new File(dirs);
                    newfile = new File(newDir, "SHOP" + date + ".txt");
                    fw = new FileOutputStream(newfile);

                    //解析获取的zip包
                    dir = dirs + fileName;
                    ZipFile zf = new ZipFile(dir);
                    InputStream in = new BufferedInputStream(new FileInputStream(dir));
                    Charset gbk = Charset.forName("UTF-8");
                    ZipInputStream zin = new ZipInputStream(in, gbk);
                    ZipEntry ze;
                    while ((ze = zin.getNextEntry()) != null) {
                        if (ze.toString().endsWith("txt")) {
                            BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze), "UTF-8"));
                            String line;
                            while ((line = br.readLine()) != null) {

                                line = line.replace("\t", "$");
//
                                String sbstr = AESUtil.Encrypt(line, transactionKey) + "\n";
                                fw.write(sbstr.getBytes("UTF-8"));
                            }
                            br.close();
                        }
                    }

                    zin.closeEntry();
                    in.close();
                    try {
                        fw.flush();
                        fw.close();
                        zf.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                } else {
                    log.debug(date + "对账文件名：" + fileName + "获取文件失败：" + returnCode);
                }
            }


        } catch (Exception e) {
            log.error("jhdzQuery异常", e);
        }

        new File(dir).delete();
        try {
            String path = newfile.getPath();
            String sig = newfile.getName();
            if (newfile.length() > 0) {

                log.debug("上传路径：" + url);
                log.debug("文件路径：" + path);
                log.debug("文件名称：" + sig);
                String retStr = upload(url, path, sig);
                log.debug("上传文件返回值：" + retStr);
//                newfile.delete();
                if (!StringUtil.isEmpty(retStr)) {
                    Map retMap = new Gson().fromJson(retStr, Map.class);
                    if (retMap != null && "200".equals(retMap.get("rspcode"))) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }

        } catch (Exception e) {
            log.error("jhdzQuery异常", e);
            throw new RRException(e.getMessage());
        }

        return false;
    }

    /***
     * 1.4轮询回调
     * @return
     * @throws RRException
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void notifyQuery() throws RRException {
        String url = configBeanValue.outConnClientInsertTysJsxx;
        try {

            String[] outConnClientMinutes = configBeanValue.outConnClientMinutes.split(",");
            int minutesStart = new Integer(outConnClientMinutes[0]);
            int minutesEnd = new Integer(outConnClientMinutes[1]);
            QueryWrapper<PayInfoEntity> queryWrapper = new QueryWrapper<>();
            Date minutesStartDate = DateUtils.addDateMinutes(new Date(), minutesStart);
            Date minutesEndDate = DateUtils.addDateMinutes(new Date(), minutesEnd);
            queryWrapper.ge("CREATED_TIME", DateUtils.format(minutesStartDate, DateUtils.DATE_TIME_PATTERN));//>=
            queryWrapper.le("CREATED_TIME", DateUtils.format(minutesEndDate, DateUtils.DATE_TIME_PATTERN));
            queryWrapper.eq("TYPE", "N");
            queryWrapper.in("BUS_STATUS", 1, 2);
//            queryWrapper.eq("BUS_STATUS", 2);
            List<PayInfoEntity> list = baseMapper.selectList(queryWrapper);

            for (int i = 0; i < list.size(); i++) {
                PayInfoEntity entity = list.get(i);
                String ORDERID = entity.getOrderId();
                String transactionKey = keyConfig.getInstance().getTransactionKey();
                String mackey = keyConfig.getInstance().getMacKey();
                //商户客户端数据查询交易是否成功
                if (!sendSocketRequest(ORDERID, entity)) {
//                    entity.setBusStatus("2");
//                    entity.setRemarks("商户客户端查询失败(notifyQuery)");
//                    baseMapper.updateById(entity);
                    continue;
                } else {
                    entity.setBusStatus("1");
                    entity.setRemarks("");
                    baseMapper.updateById(entity);
                }

                log.info("第四步:通知分行支付成功");
                StringBuffer value = new StringBuffer();
                value.append("&ywh=" + URLEncoder.encode(AESUtil.Encrypt(entity.getBusiNo(), transactionKey), "UTF-8"));//业务号
                value.append("&pid=" + URLEncoder.encode(AESUtil.Encrypt(entity.getPid(), transactionKey), "UTF-8"));//pid
                value.append("&qs=" + URLEncoder.encode(AESUtil.Encrypt(entity.getArea(), transactionKey), "UTF-8"));//区属
                value.append("&skyh=" + URLEncoder.encode(AESUtil.Encrypt("4", transactionKey), "UTF-8"));//收款银行
                value.append("&jffs=" + URLEncoder.encode(AESUtil.Encrypt("4", transactionKey), "UTF-8"));//缴费方式
                value.append("&jfje=" + URLEncoder.encode(AESUtil.Encrypt(entity.getMoney().toString(), transactionKey), "UTF-8"));//缴费金额
                value.append("&jfsj=" + URLEncoder.encode(AESUtil.Encrypt(DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN), transactionKey), "UTF-8"));//缴费时间
                value.append("&order_id=" + URLEncoder.encode(AESUtil.Encrypt(entity.getOrderId(), transactionKey), "UTF-8"));//订单号
                String macKey = ISOUtil.dumpString(MacUtils.makeMAC(mackey.getBytes(), (entity.getBusiNo() + entity.getOrderId()).getBytes()));
                value.append("&MAC=" + macKey);//MAC
                log.debug("传参：" + value.toString());
                log.debug("路径：" + url);
                String retStr = HttpClientUtils.sendPost(url, value.toString());
                log.info("支付结果通知：" + retStr);
                retStr = AESUtil.Decrypt(URLDecoder.decode(retStr, "UTF-8"), transactionKey);
//                log.debug("查询返回结果集(解密)：" + retStr);
                Map retMap = new Gson().fromJson(retStr, Map.class);
                Map returnMap = new HashMap();
                if (retMap != null && "200".equals(retMap.get("rspcode"))) {
                    log.info("第三步:更新订单流水状态(支付成功)");
                    entity.setType("Y");
                    entity.setAccType("1");
                    baseMapper.updateById(entity);
                } else if (retMap != null && "498".equals(retMap.get("rspcode"))) {
                    keyConfig.getInstance().initMacKey();
                } else if (retMap != null && "499".equals(retMap.get("rspcode"))) {
                    keyConfig.getInstance().initTransKey();
                } else {
                    continue;
                }

            }

        } catch (Exception e) {
            log.error("notifyQuery异常", e);
        }
    }


    public String upload(String requestURL, String picPath, String sig) throws RRException {

        try {
            HttpIOUtil httpReuqest = new HttpIOUtil();

            Map<String, String> requestText = new HashMap<String, String>();
            requestText.put("sig", sig);
//            Map<String, MultipartFile> requestFile = new HashMap<String, MultipartFile>();

            File file = new File(picPath);

            MultipartFile multipartFile = null;

            DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("billfile", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());

            try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
                IOUtils.copy(input, os);
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid file: " + e, e);
            }

            multipartFile = new CommonsMultipartFile(fileItem);

            String ret = httpReuqest.sendRequest(requestURL, requestText, multipartFile);

            return ret;
        } catch (Exception e) {
            log.error("upload异常", e);
            throw new RRException(e.getMessage());
        }

    }
}
